import 'package:app_settings/app_settings.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:permission_handler/permission_handler.dart';

class PermissionCheckController extends GetxController {
  final _box = GetStorage();
  final String _accessibilityConfirmedKey = 'accessibility_confirmed';

  // 【新增】通知权限状态
  final RxBool isNotificationGranted = false.obs;
  final RxBool isBatteryOptimizationIgnored = false.obs;
  final RxBool isAccessibilityConfirmed = false.obs;

  @override
  void onReady() {
    super.onReady();
    checkAllPermissions();
  }

  Future<void> checkAllPermissions() async {
    // 【新增】检查通知权限
    isNotificationGranted.value = await Permission.notification.isGranted;
    isBatteryOptimizationIgnored.value = await Permission.ignoreBatteryOptimizations.isGranted;
    isAccessibilityConfirmed.value = _box.read(_accessibilityConfirmedKey) ?? false;
  }
  
  // 【新增】请求通知权限
  Future<void> requestNotificationPermission() async {
      await Permission.notification.request();
      await checkAllPermissions(); // 请求后刷新状态
  }

  Future<void> requestBatteryOptimization() async {
    await Permission.ignoreBatteryOptimizations.request();
    await checkAllPermissions();
  }

  Future<void> gotoAccessibilitySettings() async {
    await AppSettings.openAppSettings(type: AppSettingsType.accessibility);
    Get.defaultDialog(
      title: "请确认操作",
      middleText: "您是否已经在系统设置中成功开启了[抢单助手]的无障碍服务？",
      textConfirm: "是的，我已开启",
      textCancel: "否，我未开启",
      onConfirm: () {
        _box.write(_accessibilityConfirmedKey, true);
        isAccessibilityConfirmed.value = true;
        Get.back();
        Get.snackbar("状态更新", "无障碍服务已被标记为“已开启”", backgroundColor: Colors.green, colorText: Colors.white);
      },
      onCancel: () {
        _box.write(_accessibilityConfirmedKey, false);
        isAccessibilityConfirmed.value = false;
        Get.back();
      }
    );
  }
}